﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using RxxAdmin.Extensions.AOP;
using RxxAdmin.IServices;
using RxxAdmin.Repository;
using RxxAdmin.Services;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace RxxAdmin.Extensions;

public class AutofacModuleRegister : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var basePath = AppContext.BaseDirectory;
        #region 带有接口层的服务注入

        var servicesDllFile = Path.Combine(basePath, "RxxAdmin.Services.dll");
        var repositoryDllFile = Path.Combine(basePath, "RxxAdmin.Repository.dll");

        if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
        {
            var msg = "Repository.dll和service.dll 丢失，因为项目解耦了，所以需要先F6编译，再F5运行，请检查 bin 文件夹，并拷贝。";
            Log.Error(msg);
            throw new Exception(msg);
        }

        var aopTypes = new List<Type>() { typeof(ServiceAOP) };
        builder.RegisterType<ServiceAOP>();

        builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency(); //注册仓储
        builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>))
            //.EnableInterfaceInterceptors()
            //.InterceptedBy(aopTypes.ToArray())
            .InstancePerDependency();     //注册服务

        // 获取 Service.dll 程序集服务，并注册
        var assemblysServices = Assembly.LoadFrom(servicesDllFile);
        builder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerDependency()
            .PropertiesAutowired()
            .EnableInterfaceInterceptors()
            .InterceptedBy(aopTypes.ToArray());

        // 获取 Repository.dll 程序集服务，并注册
        var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
        builder.RegisterAssemblyTypes(assemblysRepository)
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .InstancePerDependency();
        #endregion
    }
}